package com.flute.tools.sql;

import java.io.Serializable;

import com.flute.tools.util.SerializeUtil;

public class SelectSQL implements ISQL, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1005831042004398319L;
	private FieldsSQL fields;
	private SQLTable tables;
	private WhereSQL where;
	private OrderBySQL orderBy;
	private GroupBySQL groupBy;
	private LimitSQL limit;

	public SelectSQL() {
		this.tables = new SQLTable();
		this.fields = new FieldsSQL();
		this.where = new WhereSQL();
		this.orderBy = new OrderBySQL();
		this.groupBy = new GroupBySQL();
		this.limit = new LimitSQL();
	}

	public void addField(String field) {
		this.fields.addField(field);
	}

	public void addFields(String[] fields) {
		this.fields.addFields(fields);
	}

	public void addTable(String table) {
		this.tables.addTable(table);
	}

	public void addWhereCondition(String field, String value) {
		this.where.addCondition(field, value);
	}

	public void addWhereCondition(SQLCondition condition) {
		this.where.addCondition(condition);
	}

	public void addGroupByField(String field) {
		this.groupBy.addField(field);
	}

	public void addGroupByFields(String[] fields) {
		for (String field : fields) {
			this.groupBy.addField(field);
		}
	}

	public FieldsSQL getFields() {
		return fields;
	}

	public void setFields(FieldsSQL fields) {
		this.fields = fields;
	}

	public SQLTable getTables() {
		return tables;
	}

	public void setTables(SQLTable tables) {
		this.tables = tables;
	}

	public WhereSQL getWhere() {
		return where;
	}

	public void setWhere(WhereSQL where) {
		this.where = where;
	}

	public OrderBySQL getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(OrderBySQL orderBy) {
		this.orderBy = orderBy;
	}

	public GroupBySQL getGroupBy() {
		return groupBy;
	}

	public void setGroupBy(GroupBySQL groupBy) {
		this.groupBy = groupBy;
	}

	public LimitSQL getLimit() {
		return limit;
	}

	public void setLimit(LimitSQL limit) {
		this.limit = limit;
	}

	public void addOrderByField(String field, boolean desc) {
		if (!desc) {
			this.orderBy.addField(field);
		} else {
			this.orderBy.addDescField(field);
		}
	}

	public void setLimitStart(int start) {
		this.limit.setStart(start);
	}

	public void setLimitCount(int count) {
		this.limit.setCount(count);
	}

	public SelectSQL clone() {
		return (SelectSQL) SerializeUtil.ByteToObject(SerializeUtil
				.ObjectToByte(this));
	}

	@Override
	public String getSQLString() {
		String field = fields.size() == 0 ? "*" : fields.getSQLString();
		String sql = "select " + field + " from " + tables.getSQLString()
				+ where.getSQLString() + orderBy.getSQLString()
				+ groupBy.getSQLString() + limit.getSQLString();

		return SQLUtils.removeMultiBlank(sql.trim());
	}
}
